package com.huangpeng.designmodel.singleton;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author hp
 * @Title DCL（ double check lock） 双端检锁机制-强烈推荐
 * @Package
 * @Date 2021/8/18 14:49
 * @Description 单例模式线程不安全情况下，加入双端检锁机制，通过volatile禁止指令重排
 * @Version 1.0
 */
public class SingletonDemo {
    private static ExecutorService executorService = new ThreadPoolExecutor(10,20,200L, TimeUnit.SECONDS,new LinkedBlockingDeque<>(10));
    private volatile static SingletonDemo instance = null;
    private SingletonDemo(){
        System.out.println(Thread.currentThread().getName() + "\t 构造方法SingletonDemo()");
    }
    /**
     * DCL double check lock 双端检锁机制，不一定线程安全，指令重排可能使结果不唯一
     */
    public static SingletonDemo getInstance(){
        if(instance == null){
            synchronized (SingletonDemo.class){
                if(instance == null){
                    instance = new SingletonDemo();
                }
            }
        }
        return instance;
    }
    public static void main(String[] args) {
        //并发多线程时，不加synchronized结果发生改变，没有唯一结果
        for (int i = 1; i <= 10; i++) {
            executorService.execute(() -> {
                SingletonDemo.getInstance();
            });
        }
    }
}
